<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-input v-model="searchQuery" placeholder="搜索用户名" style="width: 300px; margin-right: 10px;" clearable
              @clear="resetSearch" @keyup.enter="handleSearch">
              <template #append>
                <el-button icon="Search" @click="handleSearch" />
              </template>
            </el-input>
            <el-button type="primary" @click="addUser" size="small">添加用户</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredUsers" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="userName" label="用户名" sortable />
        <el-table-column prop="password" label="密码" sortable>
          <template #default="scope">
            <el-tag type="info">{{ scope.row.password }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">
              <el-icon>
                <EditPen />
              </el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row)">
              <el-icon>
                <DeleteFilled />
              </el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  data() {
    return {
      users: [],
      filteredUsers: [],
      searchQuery: '',
      loading: false
    }
  },
  async mounted() {
    await this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const response = await axios.get(
          "http://localhost:8080/UserMgr_Web_exploded/users",
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        this.users = response.data
        this.filteredUsers = [...this.users]
      } catch (error) {
        ElMessage.error('获取用户列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      if (!this.searchQuery) {
        this.filteredUsers = [...this.users]
        return
      }
      const query = this.searchQuery.toLowerCase()
      this.filteredUsers = this.users.filter(user =>
        user.userName.toLowerCase().includes(query)
      )
    },
    resetSearch() {
      this.searchQuery = ''
      this.filteredUsers = [...this.users]
    },
    addUser() {
      this.$router.push("/addUser")
    },
    editUser(user) {
      this.$router.push(`/editUser/${user.id}`)
    },
    async deleteUser(user) {
      try {
        await ElMessageBox.confirm('确定要删除此用户吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await axios.delete(
          `http://localhost:8080/UserMgr_war_exploded/users/${user.id}`,
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        )
        if (response.data.success) {
          ElMessage.success('删除成功')
          await this.fetchUsers()
        } else {
          ElMessage.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}
</style>